/**
 * 
 */
package org.tuestudent.grouppa;

import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;

import org.json.JSONException;
import org.tuestudent.grouppa.AppContext.ActiveScreens;

import android.app.Activity;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.support.v4.app.TaskStackBuilder;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;

/**
 * Superclass for all controllers
 * 
 * @author s121170
 * 
 */
public abstract class ViewController implements Runnable {

    public static Queue<MessageFromServer> inboundMessageQueue =
            new ConcurrentLinkedQueue<MessageFromServer>();

    @Override
    public void run() {
        while ( !inboundMessageQueue.isEmpty()) {
            onMessageReceived(inboundMessageQueue.poll());
        }

    }

    /**
     * Method for sending message to the server
     * 
     * @param message
     *            a message to be sent to the server
     */
    private void sendMessage(MessageFromApp message) {
        // TODO: send message to TCPClient
    }

    /**
     * Event function run when server sent some message/response to the user
     * This function should be overridden by specific controller, But some main
     * processing can be put here
     * 
     * @param message
     *            a message that server sent
     * @throws JSONException
     */
    public abstract void onMessageReceived(MessageFromServer message);

    /**
     * Checks if the message from server is actually an error message will
     * automatically show the error on current screen
     * 
     * @param message
     *            message from server
     * @return true iff the message is of error type
     */
    protected boolean checkForError(MessageFromServer message) {
        // CHECK: show an error in case of server error
        AppContext ctx = Main.getContext();
        if ( !message.statusOK && message.messageType.equals("error")) {
            switch (ctx.activeScreen) {
            case login:
                ctx.loginActivity.errorPopup(message.serializedArguments);
                break;
            case grouppaScreen:
                ctx.grouppaActivity.errorPopup(message.serializedArguments);
                break;
            }
            return true;
        } else if(!message.statusOK && message.messageType.equals("errorAccess") && ctx.activeScreen == ActiveScreens.grouppaScreen)
        {
            ctx.grouppaActivity.finish();
            ctx.loginActivity.errorPopup("Someone else logged into this account from another device");
            return true;
        }
        return false;
    }
    
    public enum notificationIds
    {
        chatMessageNotification,
        forumMessageNotification
    }
    /**
     * Will show an android notification
     * @param title
     * @param text
     * @param id
     */
    public void showNotification(String title, String text,String group,notificationIds id)
    {
        AppContext ctx = Main.getContext();
        Activity currentActivity = ctx.getCurrentActivity();
        Intent grouppaIntent = new Intent(currentActivity, GrouppaScreen.class);
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(currentActivity);
        grouppaIntent.putExtra("userName", ctx.currentUserName);
        grouppaIntent.putExtra("userPass", ctx.currentUserPassword);
        grouppaIntent.putExtra("accessToken", ctx.currentAccessToken);
        grouppaIntent.putExtra("notificationId", id.ordinal());
        grouppaIntent.putExtra("group", group);
        // Adds the back stack
        stackBuilder.addParentStack(GrouppaScreen.class);
        // Adds the Intent to the top of the stack
        stackBuilder.addNextIntent(grouppaIntent);
        // Gets a PendingIntent containing the entire back stack
        PendingIntent resultPendingIntent =
                stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
        
        NotificationCompat.Builder builder = new NotificationCompat.Builder(currentActivity);
        builder.setContentTitle(title);
        builder.setContentText(text);
        builder.setContentIntent(resultPendingIntent);
        builder.setSmallIcon(R.drawable.grouppa_logo32);
        builder.setAutoCancel(false);
        NotificationManager mNotificationManager =
            (NotificationManager) currentActivity.getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(id.ordinal(), builder.build());
    }
    
    /**
     * resets all the stored variables
     * ran in cases of group change , user change etc.
     */
    public abstract void reset();
}
